<?php
namespace EApiSwoole\Foundation;

use EApiSwoole\Container\Container;
use EApiSwoole\Server\HttpServer;

class Application extends Container {
    protected $basePath;
    protected $serviceProviders;
    protected $booted = false;
 const welcome="
  ______                _  _____                    _      
 |  ____|   /\         (_)/ ____|                  | |     
 | |__     /  \   _ __  _| (_____      _____   ___ | | ___ 
 |  __|   / /\ \ | '_ \| |\___ \ \ /\ / / _ \ / _ \| |/ _ \
 | |____ / ____ \| |_) | |____) \ V  V / (_) | (_) | |  __/
 |______/_/    \_\ .__/|_|_____/ \_/\_/ \___/ \___/|_|\___|
                 | |                                       
                 |_|
 ";
    protected $bootstrappers = [
        \EApiSwoole\Foundation\Bootstrap\LoadConfiguration::class,
        \EApiSwoole\Foundation\Bootstrap\RegisterFacades::class,
        \EApiSwoole\Foundation\Bootstrap\RegisterProviders::class,
        \EApiSwoole\Foundation\Bootstrap\BootProviders::class
    ];
    public function __construct($basePath = null)
    {
        if ($basePath) {
            $this->setBasePath($basePath);
        }
        $this->registerBaseBindings();
        // 加载框架驱动
        $this->bootstrap();
        echo self::welcome;
    }
    public function registerBaseBindings()
    {
        static::setInstance($this);
        $this->instance('app', $this);
        $this->instance(Application::class, $this);
    }
    public function bootstrap()
    {
        foreach ($this->bootstrappers as $bootstrapper) {
            $this->make($bootstrapper)->bootstrap($this);
        }
    }
    public function run($argv)
    {
        $server = null;
        switch ($argv[1]) {
            case 'start':
                $server = new HttpServer($this);
                break;
            default:
                break;
        }
        $server->start();
    }
    public function setBasePath($path)
    {
        $this->basePath = rtrim($path, '\/');
    }
    public function getBasePath()
    {
        return $this->basePath;
    }
    public function registerConfiguredProviders()
    {
        $privoders = $this->make('config')->get('app.priovders');
        $this->make(ProviderRegister::class)->load($privoders);
//        (new ProviderRegister($this))->load($privoders);
    }
    public function marASRegistered($provider)
    {
        $this->serviceProviders[] = $provider;
    }
    public function boot()
    {
        if ($this->booted) {
            return ;
        }
        foreach ($this->serviceProviders as $key => $provider) {
            if (\method_exists($provider, 'boot')) {
                $provider->boot();
            }
        }
        $this->booted = true;
    }
}